//
//  ViewController.m
//  EagleEye
//
//  Created by 18_李明明 on 15-1-19.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "NetHander.h"
#import "TrainController.h"
#import "QRViewController.h"
#import "ExpressController.h"
#import "BusController.h"
#import "AirplaneController.h"
#import "IllegalController.h"
#import "IpController.h"
#import "PhoneAddressController.h"
#import "CityViewController.h"
#import "UIImageView+WebCache.h"
#import "AboutUsController.h"
#import "CollectionController.h"
#import "SelectedController.h"
#import "VersionController.h"
#import "UIColor+AddColor.h"
#import <MessageUI/MessageUI.h>

#define FOUNCOUNT 6
@interface ViewController ()<CLLocationManagerDelegate, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate>
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) NSArray *founctionArr;
@property (nonatomic, strong) NSString *cityName;
// 创建3个label分别显示今天，明天，后天的天气
@property (nonatomic, strong) UILabel *currentState;
@property (nonatomic, strong) UILabel *feel;
@property (nonatomic, strong) UILabel *temperature;

// 定位属性
@property (nonatomic, strong) CLLocationManager *locationManger;
//抽屉
@property (nonatomic, strong) UIImageView *drawerView;
@property (nonatomic, strong) UITableView *drawerTableView;
// 抽屉里的数组
@property (nonatomic, strong) NSArray *setArr;
// 最底下的scrollview
@property (nonatomic, strong) UIScrollView *bigScrollView;
// 显示天气的scrollview
@property (nonatomic, strong) UIScrollView *temperatureScroll;
// 在temperatureScroll上放图片
@property (nonatomic, strong) UIImageView *backgroundView;
// 创建3个显示天气的图片
@property (nonatomic, strong) UIImageView *today;
@property (nonatomic, strong) UIImageView *tomorrow;
@property (nonatomic, strong) UIImageView *theDayAfterTomorrow;
@end
@implementation ViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mainScrollView = [[UIScrollView alloc] init];
        self.founctionArr = [NSArray arrayWithObjects:@" ", @"  ", @"   ", @"    ", @"     ", @"      ", nil];
        self.setArr = [NSArray arrayWithObjects:@"历史记录", @"用户反馈", @"关于我们", nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 抽屉
    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    
    self.bigScrollView.contentSize = CGSizeMake(WIDTH * 4 / 3, 0);
//    self.bigScrollView.pagingEnabled = YES;
    self.bigScrollView.bounces = NO;
    [self.view addSubview:self.bigScrollView];
    self.view.backgroundColor = [UIColor whiteColor];
    self.bigScrollView.scrollEnabled = NO;
    self.title = @"EagleEye";
    // 除去导航栏占用的空间
    self.navigationController.navigationBar.translucent = NO;
    // Do any additional setup after loading the view, typically from a nib.
    self.mainScrollView.frame = CGRectMake(WIDTH / 3, HEIGHT / 4, WIDTH, HEIGHT * 3 / 4);
#pragma mark 移动范围
    float moveY = (20 + (WIDTH - 40) / 4) * (FOUNCOUNT + 1) / 2;
    self.mainScrollView.contentSize = CGSizeMake(0, moveY + WIDTH / 2);
    self.mainScrollView.backgroundColor = [UIColor whiteColor];
    self.mainScrollView.bounces = NO;
    self.mainScrollView.alpha = 1;
    [self.bigScrollView addSubview:self.mainScrollView];
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    [self handledata];
    // 在view上加一个显示城市的button
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"选择城市" style:UIBarButtonItemStyleDone target:self action:@selector(targetCity:)];
    // 显示天气的scrollview
    self.temperatureScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(WIDTH / 3, 0, WIDTH, HEIGHT / 4)];
    self.temperatureScroll.contentSize = CGSizeMake(WIDTH * 3, 0);
    [self.bigScrollView addSubview:self.temperatureScroll];
    self.temperatureScroll.pagingEnabled = YES;
    self.temperatureScroll.bounces = NO;
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 3, HEIGHT / 4)];
    [self.backgroundView setImage:[UIImage imageNamed:@"mainback1.jpg"]];
    self.backgroundView.alpha = 0.5;
    [self.temperatureScroll addSubview:self.backgroundView];
    self.temperatureScroll.showsHorizontalScrollIndicator = NO;
//    self.cityButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.cityButton.frame = CGRectMake(WIDTH / 3, 0, 120, 30);
//    [self.cityButton setTitle:@"选择城市" forState:UIControlStateNormal];
//    [self.bigScrollView addSubview:self.cityButton];
//    [self.cityButton addTarget:self action:@selector(targetCity:) forControlEvents:UIControlEventTouchUpInside];
    // 设置3个label
    NSInteger labelHeight = HEIGHT / 4;
    self.temperature = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, WIDTH * 3 / 4, labelHeight)];
    // 今日天气
    self.temperature.numberOfLines = 0;
    self.temperature.font = [UIFont systemFontOfSize:17];
    self.temperature.backgroundColor = [UIColor clearColor];
    [self.temperatureScroll addSubview:self.temperature];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"left.png"] style:UIBarButtonItemStylePlain target:self action:@selector(barButtonItemTarget:)];
   
    // 明天天气
    self.currentState = [[UILabel alloc] initWithFrame:CGRectMake(10 + WIDTH, 0, WIDTH * 3 / 4, labelHeight)];
    self.currentState.numberOfLines = 0;
    [self.temperatureScroll addSubview:self.currentState];
    self.currentState.backgroundColor = [UIColor whiteColor];
    self.currentState.font = [UIFont systemFontOfSize:17];
    self.currentState.backgroundColor = [UIColor clearColor];
    
    // 后天天气
    self.feel = [[UILabel alloc] initWithFrame:CGRectMake(10 + WIDTH * 2, 0, WIDTH * 3 / 4, labelHeight)];
    self.feel.numberOfLines = 0;
    [self.temperatureScroll addSubview:self.feel];
    self.feel.backgroundColor = [UIColor whiteColor];
    self.feel.font = [UIFont systemFontOfSize:17];
    self.feel.backgroundColor = [UIColor clearColor];
    // 抽屉效果
    self.drawerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, HEIGHT)];
    [self.bigScrollView addSubview:self.drawerView];
    [self putSomethingInDrawer];
    
    self.bigScrollView.contentOffset = CGPointMake(WIDTH / 3, 0);
    self.bigScrollView.delegate = self;
    self.navigationController.navigationBar.barTintColor = [UIColor lightBlue];
}
#pragma mark 往抽屉里放东西
- (void)putSomethingInDrawer
{
    self.drawerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 3, HEIGHT) style:UITableViewStyleGrouped];
    self.drawerTableView.dataSource = self;
    self.drawerTableView.delegate = self;
    UIImageView *imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cow.jpg"]];
    imageview.frame = CGRectMake(0, 0, WIDTH / 3, 60);
    self.drawerTableView.tableHeaderView = imageview;
    
    [self.drawerView setImage:[UIImage imageNamed:@"back.jpg"]];
    self.drawerTableView.backgroundView = self.drawerView;
    [self.bigScrollView addSubview:self.drawerTableView];
}
-(void)barButtonItemTarget:(UIButton *)barbutton
{
    
    if (self.bigScrollView.contentOffset.x != 0) {
       
       self.bigScrollView.contentOffset = CGPointMake(0, 0);
        self.bigScrollView.scrollEnabled = YES;

    }else{
        self.bigScrollView.scrollEnabled = NO;
        self.bigScrollView.contentOffset = CGPointMake(WIDTH / 3, 0);
    }
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.bigScrollView.contentOffset.x > WIDTH / 6) {
        [self reduction];
    }else {
        self.bigScrollView.scrollEnabled = YES;
        self.bigScrollView.contentOffset = CGPointMake(0, 0);
    
    }
}
- (void)reduction
{
    self.bigScrollView.scrollEnabled = NO;

    self.bigScrollView.contentOffset = CGPointMake(WIDTH / 3, 0);

}
// 选择城市按钮
- (void)targetCity:(UIButton *)selectCity
{
     [self reduction];
    CityViewController *city = [[CityViewController alloc] init];
    [city setCityBlock:^(NSString *city) {
//        [selectCity setTitle:city forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem.title = city;
        [self temperatureHandle:city];
    }];
    [self presentViewController:city animated:YES completion:^{
        
    }];
//    [self.navigationController pushViewController:city animated:YES];
}



#pragma mark 创建按钮
// 处理数据
- (void)handledata
{
    // 在mainscroll上加图片
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainback1.jpg"]];
    imageView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    
    [self.mainScrollView addSubview:imageView];
    imageView.alpha = 0.5;
    // 创建几个按钮
    for (int i = 0; i < FOUNCOUNT; i++) {
        // button的宽为屏幕宽度-40/2
        float buttonWidth = (WIDTH - 40) / 2;
        // button的高为屏幕高度的一半
        float buttonHeight = buttonWidth / 2;
        // button的x坐标分奇偶分配
        float buttonX = 10 + (buttonWidth + 20) * (i % 2);
        // button的y坐标为行间距20加上button的行数
        float buttonY = 20 * (i / 2 + 1) + buttonHeight * (i / 2);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(buttonX, buttonY, buttonWidth, buttonWidth);
//        button.backgroundColor = [UIColor grayColor];
        [self.mainScrollView addSubview:button];
        // 设置button标题
        [button setTitle:[self.founctionArr objectAtIndex:i] forState:UIControlStateNormal];
        // 标题颜色
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString *pic = [NSString stringWithFormat:@"%d.png", i + 1];
        [button setBackgroundImage:[UIImage imageNamed:pic] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(targetButton:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 10;
        
    }
    //开始定位
    [self locate];    
}
#pragma mark 点击事件
// 点击不同按钮跳向不同页面
- (void)targetButton:(UIButton *)button
{
    
     [self reduction];
    NSString *founction = button.titleLabel.text;
    if ([founction isEqualToString:@" "]) {
        QRViewController *qrVC = [[QRViewController alloc] init];
        [self.navigationController pushViewController:qrVC animated:YES];
    }else if ([founction isEqualToString:@"  "]){
        ExpressController *expressVC = [[ExpressController alloc] init];
        [self.navigationController pushViewController:expressVC animated:YES];
    }else if ([founction isEqualToString:@"   "]) {
        BusController *busVC = [[BusController alloc] init];
//        busVC.str = self.cityButton.titleLabel.text;
        busVC.str = self.navigationItem.rightBarButtonItem.title;
        [self presentViewController:busVC animated:YES completion:^{
            
        }];
//        [self.navigationController pushViewController:busVC animated:YES];
    }else if ([founction isEqualToString:@"    "]) {
        TrainController *trainVC = [[TrainController alloc] init];
        [self presentViewController:trainVC animated:YES completion:^{
            
        }];
//        [self.navigationController pushViewController:trainVC animated:YES];
    }else if ([founction isEqualToString:@"飞机航班"]) {
        AirplaneController *airVC = [[AirplaneController alloc] init];
        [self.navigationController pushViewController:airVC animated:YES];
    }else if ([founction isEqualToString:@"     "]) {
        IllegalController *illegal = [[IllegalController alloc] init];
        [self.navigationController pushViewController:illegal animated:YES];
    }else if ([founction isEqualToString:@"ip"]) {
        IpController *ipVC = [[IpController alloc] init];
        [self.navigationController pushViewController:ipVC animated:YES];
    }else if ([founction isEqualToString:@"      "]) {
        PhoneAddressController *phoneVC = [[PhoneAddressController alloc] init];
        [self.navigationController pushViewController:phoneVC animated:YES];
    }
    
}
-(void)viewWillAppear:(BOOL)animated
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 开始定位
#pragma mark 定位
- (void)locate
{
    // 判断定位操作是否被允许
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManger = [[CLLocationManager alloc] init];
        self.locationManger.delegate = self;
    }else {
        // 提示用户无法进行定位操作
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请打开手机定位功能" delegate:self cancelButtonTitle:@"calcle" otherButtonTitles:@"OK", nil];
        [alert show];
    }
    [self.locationManger startUpdatingLocation];
}
// 实现协议回调的方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 根据经纬度反响地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
                NSLog(@"==---%@", placemarks);
        NSLog(@"```````%@", error);
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            self.cityName = city;
            //去掉“市”字
            if ([self.cityName hasSuffix:@"市"]) {
                self.cityName = [self.cityName substringToIndex:self.cityName.length - 1];
            }else if([self.cityName hasSuffix:@"自治州"]) {
                self.cityName = [self.cityName substringToIndex:2];
            }else if ([self.cityName hasSuffix:@"地区"]){
                self.cityName = [self.cityName substringToIndex:self.cityName.length - 2];
            }
            [self temperatureHandle:self.cityName];
            self.navigationItem.rightBarButtonItem.title = self.cityName;
//            [self.cityButton setTitle:self.cityName forState:UIControlStateNormal];
//            NSLog(@"==%@", self.cityName);
        }else if (error == nil && placemarks.count == 0) {
            NSLog(@"没有返回结果");
        }
    }];
    [manager stopUpdatingLocation];
//    NSLog(@"%@", self.cityName);
}
#pragma mark 天气
- (void)temperatureHandle:(NSString *)city;
{
    // 天气预报接口
    NSString *interface = [NSString stringWithFormat:@"http://apix.sinaapp.com/weather/?appkey=liming&city=%@", city];
    // 解析接口
    [NetHander getDataWithUrl:interface completion:^(NSData *data) {
        NSArray *dataArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.temperature.text = [[dataArr objectAtIndex:3] objectForKey:@"Title"];
        self.currentState.text = [[dataArr objectAtIndex:4] objectForKey:@"Title"];
        self.feel.text = [[dataArr objectAtIndex:5] objectForKey:@"Title"];
        
        // 图片
//        NSInteger labelHeight = HEIGHT / 4;
        
        self.today = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 3 / 4 + 10, 0, WIDTH / 4 - 10, WIDTH / 4 - 10)];
        [self.temperatureScroll addSubview:self.today];
//        self.today.image = [UIImage imageNamed:@"left.png"];
        [self.today sd_setImageWithURL:[[dataArr objectAtIndex:3] objectForKey:@"PicUrl"]];
        self.today.layer.cornerRadius = WIDTH / 8 - 5;
        self.today.layer.masksToBounds = YES;
        //self.today.alpha = 0.1;
        
        // 图片
        self.tomorrow = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 7 / 4 + 10, 0, WIDTH / 4 - 10, WIDTH / 4 - 10)];
//        self.tomorrow.image = [UIImage imageNamed:@"left.png"];
        [self.tomorrow sd_setImageWithURL:[[dataArr objectAtIndex:4] objectForKey:@"PicUrl"]];
        [self.temperatureScroll addSubview:self.tomorrow];
        self.tomorrow.layer.cornerRadius = WIDTH / 8 - 5;
        self.tomorrow.layer.masksToBounds = YES;
        // 图片
        self.theDayAfterTomorrow = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * 11 / 4 + 10, 0, WIDTH / 4 - 10, WIDTH / 4 - 10)];
//        self.theDayAfterTomorrow.image = [UIImage imageNamed:@"left.png"];
        [self.theDayAfterTomorrow sd_setImageWithURL:[[dataArr objectAtIndex:5] objectForKey:@"PicUrl"]];
        [self.temperatureScroll addSubview:self.theDayAfterTomorrow];
        self.theDayAfterTomorrow.layer.cornerRadius = WIDTH / 8 - 5;
        self.theDayAfterTomorrow.layer.masksToBounds = YES;
    }];
}
// cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.setArr.count;
}

// 创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"0502"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"0502"];
    }
    cell.textLabel.text = [self.setArr objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}
// 点击cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        SelectedController *selectVC = [[SelectedController alloc] init];
        [self.navigationController pushViewController:selectVC animated:YES];
    }else if (indexPath.row == 1) {
//        VersionController *versionVC = [[VersionController alloc] init];
//        [self.navigationController pushViewController:versionVC animated:YES];
        MFMailComposeViewController *MC = [[MFMailComposeViewController alloc] init];
        MC.mailComposeDelegate = self;
        [MC setSubject:@"用户反馈"];
        [MC setToRecipients:[NSArray arrayWithObjects:@"18940137335@163.com", nil]];
        [MC setBccRecipients:[NSArray arrayWithObjects:@"792858405@qq.com", nil]];
        [MC setMessageBody:nil isHTML:NO];
        [self presentViewController:MC animated:YES completion:^{
            
        }];
    }else if (indexPath.row == 2) {
        AboutUsController *aboutVC = [[AboutUsController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    NSLog(@"%d", result);
    [self dismissViewControllerAnimated:YES completion:^{
        if (result == 2) {
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"发送成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"O了", nil];
            [alertView show];
            
        }else if (result == 1) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"存储草稿成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }];
}

//         self.setArr = [NSArray arrayWithObjects:@"查询过的", @"收藏", @"版本信息", @"关于我们", nil];






@end
